import { Builder, By, Key } from 'selenium-webdriver'
import delay from 'delay'
import fs from 'fs'

const driver = new Builder().forBrowser('chrome').build()
driver.manage().window().maximize()

let low = 0
let mid = 0
let high = 0

let currentPage = 1
const maxPage = 3

async function start() {
  await driver.get('https://www.lagou.com')
  driver.manage().deleteAllCookies()
  const cookies = JSON.parse(fs.readFileSync('./cookies.json', 'utf-8'))
  cookies.forEach(async cookie => {
    // console.log(cookie)
    await driver.manage().addCookie(cookie)
  })
  await driver.get('https://www.lagou.com')

  await driver.findElement(By.css('#cboxLoadedContent .tab.focus')).click()
  await driver.findElement(By.css('#search_input')).sendKeys('前端', Key.ENTER)

  await delay(1500)
  
  const cities = await driver.findElements(By.css('.option__2xJt5'))
  await cities[1].click()
  
  await getData(cities[cityIndex])
  // setTimeout(async() => {
  //   const cookies = await driver.manage().getCookies()
  //   console.log(cookies)
  //   fs.writeFileSync('cookies.json', JSON.stringify(cookies))
  // }, 20000)
}

start()

const cities = ['北京', '上海', '广州', '深圳', '武汉']
let cityIndex = 0
const results = []
async function getData(city) {
  console.log(`---正在获取${city}第${currentPage}页数据---`)
  await delay(1500)
  const items = await driver.findElements(By.css('.item__10RTO'))
  const moneys = await Promise.all(items.map(async item => item.findElement(By.css('.money__3Lkgq')).getText()))
  console.log(moneys)
  moneys.forEach(money => {
    const salary = money.split('-')[0].slice(0, -1)
    salary < 10 && low++
    salary >= 10 && salary < 20 && mid++
    salary >= 20 && high++
  })
  console.log(low, mid, high)
  if (currentPage < maxPage) {
    await driver.findElement(By.css('.lg-pagination-next > .lg-pagination-item-link')).click()
    currentPage++
    await getData(cities[cityIndex])
  } else {
    results.push({
      city,
      low,
      mid,
      high
    })
    console.log(results)
    cityIndex++
    if (!cities[cityIndex]) return
    const cityArr = await driver.findElements(By.css('.option__2xJt5'))
    cityArr.forEach(async city => {
      const text = await city.getText()
      if (text === cities[cityIndex]) {
        await city.click()
      }
    })
    currentPage = 1
    low = mid = high = 0
    await getData(cities[cityIndex])
  }
}